<template>
  <el-input
    v-model="localValue"
    :placeholder="param.placeholder || `请输入${param.paramName}`"
    :maxlength="param.maxLength || 50"
    :minlength="param.minLength || 0"
    :clearable="true"
    size="medium"
    :show-word-limit="showWordLimit"
    @blur="validate"
    @input="handleInput"
  ></el-input>
</template>

<script>
export default {
  name: 'TextInput',
  props: {
    value: {
      type: [String, Object],
      required: true
    },
    param: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      localValue: ''
    }
  },
  computed: {
    showWordLimit() {
      return this.param.showWordLimit !== false
    }
  },
  watch: {
    value: {
      handler(newVal) {
        // 处理两种值格式：字符串或对象
        if (typeof newVal === 'string') {
          this.localValue = newVal
        } else if (newVal && typeof newVal === 'object') {
          this.localValue = newVal.value || ''
        } else {
          this.localValue = ''
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    handleInput(value) {
      this.emitChange(value, true, '')
    },
    
    validate() {
      const value = this.localValue
      let isValid = true
      let message = ''

      // 必填验证
      if (this.param.required && !value.trim()) {
        isValid = false
        message = this.param.validationMessage?.required || '此字段为必填项'
      }

      // 长度验证
      if (isValid && value) {
        if (this.param.minLength && value.length < this.param.minLength) {
          isValid = false
          message = `内容长度不能少于${this.param.minLength}个字符`
        }
        
        if (this.param.maxLength && value.length > this.param.maxLength) {
          isValid = false
          message = `内容长度不能超过${this.param.maxLength}个字符`
        }
      }

      // 正则验证
      if (isValid && value && this.param.pattern) {
        const regex = new RegExp(this.param.pattern)
        if (!regex.test(value)) {
          isValid = false
          message = this.param.validationMessage?.pattern || '格式不符合要求'
        }
      }

      this.emitChange(value, isValid, message)
    },
    
    emitChange(value, isValid, message) {
      this.$emit('change', {
        value: value ?? '',   // 用 ?? 避免把 0 当成空
        isValid,
        message
      })
    }
  }
}
</script>